package com.logos.jdbc.senior;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class JDBCUtil {


    // 维护一个连接池对象
    private static DataSource dataSource;

    // 维护一个线程绑定变量的ThreadLocal对象
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    // 项目启动时，即创建连接池对象，赋值给dataSource
    static {
        try {
            Properties properties = new Properties();
            InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException("JDBCUtil初始化出错！！！");
        }
    }

    /**
     * 对外提供在ThreadLocal中获取连接的方法
     */
    public static Connection getConnection() {
        try {
            //在ThreadLocal中获取Connection
            Connection connection = threadLocal.get();
            //ThreadLocal里没有存储的Connection，也就是第一次获取
            if (connection == null) {
                //在连接池中获取一个连接，存储在ThreadLocal里
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (Exception e) {
            throw new RuntimeException("获取连接失败！！！");
        }
    }

    /**
     * 对外提供回收连接的方法
     */
    public static void releaseConnection() {
        try {
            Connection connection = threadLocal.get();
            if (connection != null) {
                // 从ThreadLocal中移除当前已经存储的Connection对象
                threadLocal.remove();
                connection.setAutoCommit(true);
                // 将Connection对象归还给连接池
                connection.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("回收连接失败！！！");
        }
    }
}
